package com.tanhua.sso.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.MyCenterService;
import com.tanhua.sso.service.SmsService;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class MyCenterServiceImpl implements MyCenterService {
    @Autowired
    private UserService userService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean sendVerificationCode(String token) {
        User user = this.userService.queryUserByToken(token);
        if (ObjectUtil.isEmpty(user)){
            return false;
        }
        ErrorResult errorResult = this.smsService.sendCheckCode(user.getMobile());

        return errorResult==null;
    }

    @Override
    public Boolean checkVerificationCode(String code, String token) {
        User user = this.userService.queryUserByToken(token);
        if(ObjectUtil.isEmpty(user)){
            return false;
        }
        String mobile = user.getMobile();
        String redisKey = "CHECK_CODE_" + mobile;
        String s = this.redisTemplate.opsForValue().get(redisKey);
        if (!StrUtil.equalsIgnoreCase(s,code)) {
            return false;
        }
        //删除验证码
        this.redisTemplate.delete(redisKey);

        return true;
    }

    @Override
    public boolean updatePhone(String token, String newPhone) {
        //校验token
        User user = this.userService.queryUserByToken(token);
        if(ObjectUtil.isEmpty(user)){
            return false;
        }
        Boolean result = this.userService.updatePhone(user.getId(), newPhone);
        if(result){
            String redisKey = "TANHUA_USER_MOBILE_" + user.getId();
            this.redisTemplate.delete(redisKey);
        }

        return result;
    }
}
